<template>
  <div class="course-type-page">
    <!-- 左侧菜单 -->
    <div class="menu">
      <h2>输电专业知识学习平台</h2>
      <el-menu :default-active="activeMenu" class="el-menu-vertical" @select="handleMenuSelect"
        background-color="#2c3e50" text-color="#ecf0f1" active-text-color="#ffffff">
        <el-menu-item index="category">
          <el-icon>
            <FolderOpened />
          </el-icon>
          <template #title><span>课程分类管理</span></template>
        </el-menu-item>
        <el-menu-item index="course">
          <el-icon>
            <Reading />
          </el-icon>
          <template #title><span>课程管理</span></template>
        </el-menu-item>
      </el-menu>
    </div>
    <!-- 右侧内容区域整体，包含顶部栏 + 原内容 -->
    <div class="right-container">
      <!-- 右侧内容区顶部栏 -->
      <div class="right-top-bar">
        <div class="top-bar-left">
          <span class="breadcrumb">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
              <el-breadcrumb-item>{{
                activeMenu === "category" ? "课程分类管理" : "课程管理"
              }}</el-breadcrumb-item>
            </el-breadcrumb>
          </span>
        </div>
        <div class="top-bar-right">
          <!-- 可根据实际需求添加搜索、用户信息等 -->
          <span class="user-info">欢迎，{{ username }}</span>
        </div>
      </div>
      <!-- 原右侧内容 -->
      <div class="content">
        <!-- 重新显示广告栏按钮 -->
        <div class="show-ad-btn" v-show="!showAdSidebar" @click="toggleAdSidebar">
          <el-icon>
            <Promotion />
          </el-icon>
        </div>

        <!-- 跟随屏幕移动的广告栏 -->
        <div class="floating-ad-sidebar" v-show="showAdSidebar">
          <!-- 关闭按钮 -->
          <div class="ad-close-btn" @click="toggleAdSidebar">
            <el-icon>
              <Close />
            </el-icon>
          </div>
          <!-- 顶部功能按钮区域 -->
          <div class="ad-section top-buttons">
            <div class="ad-button" @click="handleAdButtonClick('去百度看看')">
              去百度看看
            </div>
            <div class="ad-button" @click="handleAdButtonClick('去京东看看')">
              去京东看看
            </div>
            <div class="ad-button" @click="handleAdButtonClick('去淘宝看看')">
              去淘宝看看
            </div>
            <div class="ad-button" @click="handleAdButtonClick('去天猫看看')">
              去天猫看看
            </div>
            <div class="ad-button" @click="handleAdButtonClick('去拼多多看看')">
              去拼多多看看
            </div>
          </div>

          <!-- 底部红色区域 -->
          <!-- <div class="ad-section red-section">
            <div class="ad-button red-button" @click="scrollToTop">
              返回顶部
            </div>
          </div> -->
        </div>
        <!-- 课程分类管理 -->
        <div v-if="activeMenu === 'category'">
          <div class="page-title-bar">
            <h2 class="page-title">课程类型列表</h2>
            <el-button type="primary" @click="goToAddLessonType" class="add-btn">
              <i class="el-icon-plus"></i> 新增课程分类
            </el-button>
          </div>
          <el-skeleton v-if="loading" :loading="loading" :rows="6" style="padding: 20px"></el-skeleton>
          <div class="card-list" v-else>
            <div class="course-card" v-for="(item, index) in lessonTypeList" :key="index"
              @mouseenter="handleMouseEnter(index)" @mouseleave="handleMouseLeave(index)">
              <div class="card-image">
                <el-image v-if="item.lessonTypePhoto" :src="getImageBase64(item.lessonTypePhoto)" fit="cover"
                  @error="handleImageError" class="course-img" />
                <div class="placeholder" v-else>
                  <i class="el-icon-picture-outline"></i>
                  <span>暂无图片</span>
                </div>
              </div>
              <div class="card-content">
                <div class="card-header">
                  <h3 class="course-type">{{ item.lessonType }}</h3>
                  <span class="course-count-tag">
                    <i class="el-icon-book"></i> {{ item.courseCount }}门课程
                  </span>
                </div>
                <p class="description">
                  {{ item.lessonTypeDescription || "暂无描述信息" }}
                </p>
                <div class="card-actions">
                  <!-- 课程类型卡片不显示查看详情按钮 -->
                </div>
              </div>
            </div>
            <!-- 空状态处理 -->
            <div class="empty-state" v-if="lessonTypeList.length === 0">
              <el-empty description="暂无课程分类数据" />
            </div>
          </div>
        </div>
        <!-- 课程管理 -->
        <div v-else>
          <div class="page-title-bar">
            <h2 class="page-title">课程列表</h2>
            <el-button type="primary" @click="goToAddCourse" class="add-btn">
              <i class="el-icon-plus"></i> 新增课程
            </el-button>
          </div>
          <div class="card-list">
            <div class="course-card course-list" v-for="(item, index) in courseList" :key="index">
              <div class="card-image">
                <el-image v-if="item.courseImageUrl" :src="item.courseImageUrl" fit="cover" class="course-img" />
                <div class="placeholder" v-else>
                  <i class="el-icon-picture-outline"></i>
                  <span>暂无图片</span>
                </div>
              </div>
              <div class="card-content">
                <div class="card-header">
                  <span class="category-tag">{{ item.lessonTypeName }}</span>
                  <h3 class="course-name">{{ item.courseName }}</h3>
                </div>
                <p class="description">
                  {{ item.courseDescription || "暂无课程描述" }}
                </p>
                <div class="card-actions">
                  <el-button link size="small" @click.stop="handleViewCourseDetail(item)">
                    查看详情
                  </el-button>
                </div>
              </div>
            </div>
            <div class="empty-state" v-if="courseList.length === 0">
              <el-empty description="暂无课程数据" />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import {
  ElMessage,
  ElSkeleton,
  ElImage,
  ElEmpty,
  ElBreadcrumb,
  ElBreadcrumbItem,
} from "element-plus";
import axios from "axios";
import { FolderOpened, Reading } from "@element-plus/icons-vue";

const router = useRouter();
const route = useRoute();
const activeMenu = ref("category");
const showAdSidebar = ref(true); // 控制广告栏显示/隐藏
const handleMenuSelect = (index) => {
  activeMenu.value = index;
  if (index === "category") {
    router.push({ name: "CourseTypes", query: { tab: "category" } });
  } else if (index === "course") {
    router.push({ name: "CourseTypes", query: { tab: "course" } });
  }
};

const username = ref("");

// 组件挂载时获取用户信息和角色
onMounted(() => {
  const userInfoStr = localStorage.getItem("userInfo");
  if (userInfoStr) {
    const userInfo = JSON.parse(userInfoStr);
    username.value = userInfo.name;
  }
});

// 课程分类数据
const lessonTypeList = ref([]);
const loading = ref(true);

onMounted(async () => {
  // 检查路由参数，自动切换菜单
  if (route.query.tab === "course") {
    activeMenu.value = "course";
  } else {
    activeMenu.value = "category"; // 默认激活课程分类管理
  }

  try {
    const response = await axios.get(
      "/tielingpowergriduavservice/lesson-type/list"
    );
    if (response.data.code === 200) {
      lessonTypeList.value = response.data.data;
    } else {
      ElMessage.error("获取数据失败：" + response.data.msg);
    }
  } catch (error) {
    ElMessage.error("请求异常：" + error.message);
  } finally {
    loading.value = false;
  }
  // 获取课程列表
  fetchCourseList();
});

// 监听路由变化，更新菜单激活状态
watch(
  () => route.query.tab,
  (newTab) => {
    if (newTab === "course") {
      activeMenu.value = "course";
    } else {
      activeMenu.value = "category";
    }
  }
);

function getCourseImageUrl(base64) {
  if (!base64) return "";
  try {
    if (base64.startsWith("/9j/")) {
      return "data:image/jpeg;base64," + base64;
    }
    return base64;
  } catch {
    return "";
  }
}

async function fetchCourseList() {
  try {
    const res = await axios.get("/tielingpowergriduavservice/lesson/list");
    if (res.data && res.data.code === 200) {
      courseList.value = (res.data.data || []).map((item) => ({
        id: item.id,
        courseName: item.lesson,
        courseDescription: item.blurb,
        lessonTypeName: item.lessonTypeName,
        courseImageUrl: getCourseImageUrl(item.lessonPhoto),
      }));
    } else {
      courseList.value = [];
      ElMessage.error(res.data?.message || "获取课程数据失败");
    }
  } catch (e) {
    courseList.value = [];
    ElMessage.error("请求课程数据异常");
  }
}

const getImageBase64 = (byteArray) => {
  const binaryString = window.atob(byteArray);
  const len = binaryString.length;
  const uint8Array = new Uint8Array(len);
  for (let i = 0; i < len; i++) {
    uint8Array[i] = binaryString.charCodeAt(i);
  }
  const blob = new Blob([uint8Array], { type: "image/jpeg" });
  return URL.createObjectURL(blob);
};

const handleImageError = () => {
  ElMessage.warning("图片加载失败");
};

// 卡片交互
const handleMouseEnter = (index) => {
  const card = document.querySelectorAll(".course-card")[index];
  card.style.transform = " translateY(-5px)";
  card.style.boxShadow = "0 10px 25px rgba(0,0,0,0.1)";
};
const handleMouseLeave = (index) => {
  const card = document.querySelectorAll(".course-card")[index];
  card.style.transform = "translateY(0)";
  card.style.boxShadow = "0 4px 15px rgba(0,0,0,0.05)";
};

// 跳转新增课程分类
const goToAddLessonType = () => {
  router.push("/lesson-type/add");
};

// 课程列表和新增课程按钮
const courseList = ref([]);

const goToAddCourse = () => {
  router.push("/course/add");
};

// 查看详情方法
const handleViewCourseDetail = (item) => {
  router.push({
    path: "/course/detail",
    query: { id: item.id },
  });
};

// 返回顶部功能
// const scrollToTop = () => {
//   window.scrollTo({
//     top: 0,
//     behavior: "smooth",
//   });
// };

// 广告栏按钮点击处理
const handleAdButtonClick = (buttonText) => {
  let url = "";

  switch (buttonText) {
    case "去百度看看":
      url = "https://www.baidu.com";
      break;
    case "去京东看看":
      url = "https://www.jd.com";
      break;
    case "去淘宝看看":
      url = "https://www.taobao.com";
      break;
    case "去天猫看看":
      url = "https://www.tmall.com";
      break;
    case "去拼多多看看":
      url = "https://www.pinduoduo.com";
      break;
    default:
      ElMessage({
        message: `点击了：${buttonText}`,
        type: "info",
        duration: 2000,
      });
      return;
  }

  // 在新窗口中打开对应官网
  window.open(url, "_blank");
};

// 切换广告栏显示/隐藏
const toggleAdSidebar = () => {
  showAdSidebar.value = !showAdSidebar.value;
};
</script>

<style scoped>
.back-home-btn-bar {
  display: none;
}

.back-home-btn {
  display: none;
}

.back-home-btn-in-menu {
  width: 80%;
  margin: 0 auto 18px auto;
  display: block;
  font-size: 15px;
  color: #3498db;
  background: #fff;
  border-radius: 18px;
  box-shadow: 0 2px 8px rgba(52, 152, 219, 0.08);
  padding: 7px 0;
  border: none;
  transition: background 0.2s;
}

.back-home-btn-in-menu:hover {
  background: #eaf6fb;
  color: #217dbb;
}

.course-type-page {
  background-color: #f8fafc;
  min-height: calc(100vh - 80px);
  display: flex;
  overflow: hidden;
  position: relative;
}

/* 左侧菜单优化 */
.menu {
  width: 250px;
  min-width: 220px;
  max-width: 300px;
  background: #2c3e50;
  color: #ecf0f1;
  padding: 20px 0;
  min-height: 100vh;
  height: auto;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.05);
  z-index: 10;
  position: fixed;
  left: 0;
  top: 0;
}

.menu h2 {
  font-size: 18px;
  font-weight: 500;
  padding: 0 20px;
  text-align: center;
  margin: 0 0 18px;
  height: 40px;
  line-height: 40px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  width: 80%;
}

/* 菜单样式覆盖 */
:deep(.el-menu-vertical) {
  width: 100%;
  margin-top: 20px;
  background-color: transparent !important;
}

:deep(.el-menu-item) {
  height: 50px;
  line-height: 50px;
  margin: 0 10px;
  border-radius: 6px;
  color: #bdc3c7;
  transition: all 0.3s;
}

:deep(.el-menu-item.is-active) {
  background-color: #199893 !important;
  color: #ffffff !important;
}

:deep(.el-menu-item:hover:not(.is-active)) {
  background-color: rgba(255, 255, 255, 0.05) !important;
  color: #ecf0f1 !important;
}

:deep(.el-menu-item i) {
  margin-right: 12px;
  font-size: 16px;
}

/* 右侧内容区域整体容器 */
.right-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  margin-left: 250px;
  /* 为固定的左侧菜单留出空间 */
}

/* 右侧内容区顶部栏 */
.right-top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  padding: 0 20px;
  height: 50px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  z-index: 9;
}

.right-top-bar .top-bar-left {
  display: flex;
  align-items: center;
}

.right-top-bar .breadcrumb {
  font-size: 14px;
  color: #666;
}

.right-top-bar .top-bar-right {
  color: #333;
}

.right-top-bar .user-info {
  line-height: 50px;
}

/* 原右侧内容区样式调整，让内容在顶部栏下方 */
.content {
  flex: 1;
  padding: 30px 50px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  position: relative;
}

/* 标题栏优化 */
.page-title-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e2e8f0;
}

.page-title {
  font-size: 22px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0;
  display: flex;
  align-items: center;
}

.page-title::before {
  content: "";
  display: inline-block;
  width: 4px;
  height: 20px;
  background-color: #3498db;
  margin-right: 10px;
  border-radius: 2px;
}

.add-btn {
  background-color: #3498db;
  border-color: #3498db;
  transition: all 0.3s;
}

.add-btn:hover {
  background-color: #2980b9;
  border-color: #2980b9;
}

/* 卡片列表优化 */
.card-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  justify-content: flex-start;
  margin-right: 140px;
  /* 为广告栏留出空间 */
}

.course-card {
  width: calc((100% - 80px) / 5);
  /* 一行5个卡片，减去4个间距 */
  min-width: 200px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;
  position: relative;
}

/* 卡片图片区域 */
.card-image {
  width: 100%;
  height: 160px;
  overflow: hidden;
  position: relative;
}

.course-img {
  width: 100%;
  height: 100%;
  transition: transform 0.5s ease;
}

.course-card:hover .course-img {
  transform: scale(1.05);
}

.placeholder {
  width: 100%;
  height: 160px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #f8fafc;
  color: #95a5a6;
  font-size: 14px;
}

.placeholder i {
  font-size: 24px;
  margin-bottom: 8px;
  color: #bdc3c7;
}

/* 卡片内容区域 */
.card-content {
  padding: 20px;
}

.card-header {
  display: flex;
  flex-direction: column;
  margin-bottom: 12px;
}

.course-type {
  font-size: 18px;
  font-weight: 500;
  color: #2c3e50;
  margin: 0 0 8px 0;
  line-height: 1.3;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.course-count-tag {
  display: inline-flex;
  align-items: center;
  padding: 3px 8px;
  font-size: 12px;
  color: #7f8c8d;
  background-color: #f1f5f9;
  border-radius: 4px;
  margin-bottom: 10px;
  width: fit-content;
}

.course-count-tag i {
  margin-right: 5px;
  font-size: 12px;
}

.category-tag {
  display: inline-block;
  padding: 3px 8px;
  font-size: 16px;
  font-weight: 500;
  color: #3498db;
  background-color: #ebf5fb;
  border-radius: 4px;
  margin-bottom: 8px;
}

.course-name {
  font-size: 17px;
  font-weight: 500;
  color: #2c3e50;
  margin: 0 0 10px 0;
  line-height: 1.3;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.description {
  font-size: 14px;
  color: #7f8c8d;
  margin: 0 0 15px 0;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  height: 63px;
  /* 固定高度确保卡片对齐 */
}

/* 卡片操作区 */
.card-actions {
  display: flex;
  justify-content: flex-end;
  padding-top: 10px;
}

/* 仅课程列表卡片显示横线，课程类型卡片不显示 */
.course-card .card-actions {
  border-top: none;
}

.course-card.course-list .card-actions {
  border-top: 1px solid #f1f5f9;
}

:deep(.el-button--link) {
  color: #3498db;
  padding: 5px 10px;
}

:deep(.el-button--link:hover) {
  color: #2980b9;
  background-color: rgba(52, 152, 219, 0.05);
}

/* 空状态样式 */
.empty-state {
  width: 100%;
  padding: 60px 0;
  display: flex;
  justify-content: center;
}

/* 优化后的广告栏样式 */
.floating-ad-sidebar {
  position: fixed;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  width: 140px;
  background: linear-gradient(145deg, #ffffff, #f8f9fa);
  border-radius: 12px;
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  border: 1px solid rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.floating-ad-sidebar:hover {
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
}

.ad-close-btn {
  position: absolute;
  top: 6px;
  right: 6px;
  width: 24px;
  height: 24px;
  background: rgba(0, 0, 0, 0.05);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #666;
  font-size: 12px;
  transition: all 0.3s;
  z-index: 1001;
}

.ad-close-btn:hover {
  background: rgba(0, 0, 0, 0.1);
  color: #333;
  transform: rotate(90deg);
}

.ad-section {
  padding: 12px 0;
}

.top-buttons {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 12px;
}

.ad-button {
  display: flex;
  align-items: center;
  padding: 10px 12px;
  background: rgba(255, 255, 255, 0.9);
  color: #444;
  font-size: 13px;
  font-weight: 500;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.ad-button:hover {
  background: #fff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: rgba(0, 0, 0, 0.1);
}

.ad-button i {
  margin-right: 8px;
  font-size: 16px;
  color: #555;
}

/* 为每个按钮添加独特的颜色效果 */
.ad-button:nth-child(1) {
  color: #1890ff;
  border-left: 3px solid #1890ff;
}

.ad-button:nth-child(1):hover {
  background: rgba(24, 144, 255, 0.05);
}

.ad-button:nth-child(1) i {
  color: #1890ff;
}

.ad-button:nth-child(2) {
  color: #f5222d;
  border-left: 3px solid #f5222d;
}

.ad-button:nth-child(2):hover {
  background: rgba(245, 34, 45, 0.05);
}

.ad-button:nth-child(2) i {
  color: #f5222d;
}

.ad-button:nth-child(3) {
  color: #fa8c16;
  border-left: 3px solid #fa8c16;
}

.ad-button:nth-child(3):hover {
  background: rgba(250, 140, 22, 0.05);
}

.ad-button:nth-child(3) i {
  color: #fa8c16;
}

.ad-button:nth-child(4) {
  color: #722ed1;
  border-left: 3px solid #722ed1;
}

.ad-button:nth-child(4):hover {
  background: rgba(114, 46, 209, 0.05);
}

.ad-button:nth-child(4) i {
  color: #722ed1;
}

.ad-button:nth-child(5) {
  color: #13c2c2;
  border-left: 3px solid #13c2c2;
}

.ad-button:nth-child(5):hover {
  background: rgba(19, 194, 194, 0.05);
}

.ad-button:nth-child(5) i {
  color: #13c2c2;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .floating-ad-sidebar {
    width: 120px;
  }

  .ad-button {
    padding: 8px 10px;
    font-size: 12px;
  }

  .ad-button i {
    font-size: 14px;
    margin-right: 6px;
  }
}

.red-section {
  background: #c41e3a;
  color: white;
  margin: 0;
  padding: 8px;
  text-align: center;
}

.red-button {
  background: #c41e3a;
  color: white;
  margin: 0;
  width: 100%;
}

.red-button:hover {
  background: #a01830;
}

/* 响应式优化 */
@media (max-width: 1400px) {
  .course-card {
    width: calc((100% - 60px) / 4);
    /* 一行4个卡片 */
  }
}

@media (max-width: 1200px) {
  .course-card {
    width: calc((100% - 40px) / 3);
    /* 一行3个卡片 */
  }

  .card-list {
    margin-right: 140px;
    /* 保持为广告栏留出空间 */
  }
}

@media (max-width: 992px) {
  .course-card {
    width: calc((100% - 20px) / 2);
    /* 一行2个卡片 */
  }

  .content {
    padding: 20px 30px;
  }

  .floating-ad-sidebar,
  .show-ad-btn {
    display: none;
    /* 在中等屏幕上隐藏广告栏和显示按钮 */
  }

  .card-list {
    margin-right: 0;
    /* 移除右边距 */
  }
}

@media (max-width: 768px) {
  .menu {
    width: 70px;
    min-width: 70px;
  }

  .menu h2,
  :deep(.el-menu-item span) {
    display: none;
  }

  :deep(.el-menu-item i) {
    margin-right: 0;
    font-size: 18px;
  }

  :deep(.el-menu-item) {
    justify-content: center;
  }

  .right-container {
    margin-left: 70px;
    /* 调整小屏幕下的左边距 */
  }

  .course-card {
    width: 100%;
  }
}

@media (max-width: 576px) {
  .page-title-bar {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .add-btn {
    width: 100%;
  }
}
</style>
